import axios from 'axios'
import { Message } from 'element-ui'

// import store from '../store'
// import { getToken } from '@/utils/auth'

// 创建axios实例
const service = axios.create({
	baseURL: process.env.BASE_API, // api的base_url
	timeout: 15000 // 请求超时时间
})
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'
axios.defaults.headers.put['Content-Type'] = 'application/json;charset=UTF-8'
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
axios.defaults.headers.delete['Content-Type'] = 'application/json;charset=UTF-8'
// request拦截器，发出请求前在header里添加token
service.interceptors.request.use(function(config) {
	config.headers['token'] = window.sessionStorage.getItem('token')
	return config
}, function(error) {
	return Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(response => {
		if (response.data.errorCode !== 'E_000') {
			Message({
				message: response.data.message,
				type: 'error',
				duration: 2 * 1000
			})
		}
		return response
	},
	error => {
		if (error.response.status === 401) {
			// 没有权限访问，请登录
			let a = window.location.origin.concat('/#/login')
			window.location.href = a
		} else if (error.response.status === 400) {
			var msg = ''
			for (var i in error.response.data.body) {
				if (i === 0) {
					msg = error.response.data.body[i].message
				} else {
					msg = msg + error.response.data.body[i].message + ';'
				}
			}
			Message({
				message: msg,
				type: 'error',
				duration: 2 * 1000
			})
		} else if (error.response.status === 404) {
			Message({
				message: '客户端请求路径不存在',
				type: 'error',
				duration: 2 * 1000
			})
		} else if (error.response.status === 555) {
			Message({
				message: '系统异常',
				type: 'error',
				duration: 2 * 1000
			})
		} else if (error.response.status === 500) {
			Message({
				message: '系统异常',
				type: 'error',
				duration: 2 * 1000
			})
		} else {
			return Promise.reject(error)
		}
	}
)

export default service
